import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { 
  Card, 
  Button, 
  Descriptions, 
  Tabs, 
  message, 
  Spin, 
  Layout, 
  Row, 
  Col, 
  Select, 
  Input,
  Table,
  Tag,
  Space
} from 'antd';
import { 
  ArrowLeftOutlined, 
  SearchOutlined,
  ReloadOutlined
} from '@ant-design/icons';
import { kubernetesApi } from '../services/api';
import './VersionDetailPage.css';

const { Content } = Layout;
const { TabPane } = Tabs;
const { Option } = Select;

const VersionDetailPage = () => {
  const { projectId, versionId } = useParams();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [versionData, setVersionData] = useState(null);
  const [activeTab, setActiveTab] = useState('deployment');
  
  // 集群、环境、命名空间数据
  const [clusterInfo, setClusterInfo] = useState({
    cluster: '生产集群',
    environment: '生产环境',
    namespace: 'default'
  });
  
  // 从接口获取集群信息
  useEffect(() => {
    const fetchClusterInfo = async () => {
      try {
        // 这里替换为实际的API调用
        // const response = await kubernetesApi.getClusterInfo(projectId, versionId);
        // setClusterInfo(response.data);
        
        // 模拟数据
        const mockData = {
          cluster: 'production-cluster',
          environment: 'production',
          namespace: 'default'
        };
        setClusterInfo({
          cluster: '生产集群',
          environment: '生产环境',
          namespace: mockData.namespace
        });
      } catch (error) {
        console.error('获取集群信息失败:', error);
        message.error('获取集群信息失败');
      }
    };
    
    if (projectId && versionId) {
      fetchClusterInfo();
    }
  }, [projectId, versionId]);
  
  // 表格列定义
  const deploymentColumns = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '命名空间',
      dataIndex: 'namespace',
      key: 'namespace',
    },
    {
      title: '副本',
      dataIndex: 'replicas',
      key: 'replicas',
      render: (_, record) => (
        <span>{record.availableReplicas || 0}/{record.replicas || 0}</span>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <Tag color={status === 'Running' ? 'green' : 'red'}>
          {status}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'creationTimestamp',
      key: 'creationTimestamp',
    },
  ];

  useEffect(() => {
    const fetchVersionDetails = async () => {
      try {
        setLoading(true);
        // Replace with actual API call to fetch version details
        // const response = await kubernetesApi.getVersionDetails(projectId, versionId);
        // setVersionData(response.data);
        
        // Mock data for now
        setTimeout(() => {
          setVersionData({
            id: versionId,
            name: `version-${versionId}`,
            projectId,
            status: 'Active',
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString(),
            // Add more details as needed
          });
          setLoading(false);
        }, 500);
      } catch (error) {
        console.error('Failed to fetch version details:', error);
        message.error('Failed to load version details');
        setLoading(false);
      }
    };

    fetchVersionDetails();
  }, [projectId, versionId]);

  const handleBack = () => {
    navigate('/releases');
  };

  if (loading) {
    return (
      <div className="version-detail-loading">
        <Spin size="large" />
      </div>
    );
  }

  // 格式化环境显示名称
  const getEnvironmentName = (env) => {
    const envMap = {
      'dev': '开发环境',
      'test': '测试环境',
      'staging': '预发环境',
      'production': '生产环境'
    };
    return envMap[env] || env;
  };
  
  // 模拟表格数据
  const mockTableData = [
    {
      key: '1',
      name: versionData?.name || 'app-example',
      namespace: clusterInfo.namespace || 'default',
      replicas: 2,
      availableReplicas: 2,
      status: 'Running',
      creationTimestamp: new Date().toLocaleString(),
    },
  ];

  return (
    <Layout className="site-layout" style={{ minHeight: '100vh' }}>
      <Content style={{ margin: '0 16px', padding: '24px 0' }}>
        <div className="version-detail-container">
          <div className="page-header">
            <Button 
              type="text" 
              icon={<ArrowLeftOutlined />} 
              onClick={handleBack}
              style={{ marginRight: 16 }}
            >
              返回
            </Button>
            <h2 style={{ margin: 0, flex: 1 }}>{versionData?.name || '版本详情'}</h2>
          </div>
          
          {/* 集群信息展示 */}
          <Card className="info-card" style={{ marginBottom: 16 }}>
            <Row gutter={24}>
              <Col span={8}>
                <div className="info-item">
                  <span className="info-label">集群：</span>
                  <span className="info-value">{clusterInfo.cluster}</span>
                </div>
              </Col>
              <Col span={8}>
                <div className="info-item">
                  <span className="info-label">环境：</span>
                  <span className="info-value">{clusterInfo.environment}</span>
                </div>
              </Col>
              <Col span={8}>
                <div className="info-item">
                  <span className="info-label">命名空间：</span>
                  <span className="info-value">{clusterInfo.namespace}</span>
                </div>
              </Col>
            </Row>
          </Card>
          
          {/* 内容区域 */}
          <div className="section-container">
            {/* Deployment 部分 */}
            <Card 
              title={
                <div className="section-header">
                  <h3>Deployment</h3>
                  <Space>
                    <Input 
                      placeholder="搜索..." 
                      prefix={<SearchOutlined />} 
                      style={{ width: 200 }}
                    />
                    <Button icon={<ReloadOutlined />} onClick={() => window.location.reload()} />
                  </Space>
                </div>
              }
              className="section-card"
            >
              <Table 
                columns={deploymentColumns} 
                dataSource={mockTableData} 
                rowKey="name"
                pagination={false}
              />
            </Card>

            {/* Pod 部分 */}
            <Card 
              title={
                <div className="section-header">
                  <h3>Pod</h3>
                  <Space>
                    <Input 
                      placeholder="搜索..." 
                      prefix={<SearchOutlined />} 
                      style={{ width: 200 }}
                    />
                    <Button icon={<ReloadOutlined />} onClick={() => window.location.reload()} />
                  </Space>
                </div>
              }
              className="section-card"
            >
              <div className="tab-content">
                <p>Pod 信息将显示在这里</p>
              </div>
            </Card>

            {/* Service 部分 */}
            <Card 
              title={
                <div className="section-header">
                  <h3>Service</h3>
                  <Space>
                    <Input 
                      placeholder="搜索..." 
                      prefix={<SearchOutlined />} 
                      style={{ width: 200 }}
                    />
                    <Button icon={<ReloadOutlined />} onClick={() => window.location.reload()} />
                  </Space>
                </div>
              }
              className="section-card"
            >
              <div className="tab-content">
                <p>Service 信息将显示在这里</p>
              </div>
            </Card>

            {/* Ingress 部分 */}
            <Card 
              title={
                <div className="section-header">
                  <h3>Ingress</h3>
                  <Space>
                    <Input 
                      placeholder="搜索..." 
                      prefix={<SearchOutlined />} 
                      style={{ width: 200 }}
                    />
                    <Button icon={<ReloadOutlined />} onClick={() => window.location.reload()} />
                  </Space>
                </div>
              }
              className="section-card"
            >
              <div className="tab-content">
                <p>Ingress 信息将显示在这里</p>
              </div>
            </Card>

            {/* ServiceMonitor 部分 */}
            <Card 
              title={
                <div className="section-header">
                  <h3>ServiceMonitor</h3>
                  <Space>
                    <Input 
                      placeholder="搜索..." 
                      prefix={<SearchOutlined />} 
                      style={{ width: 200 }}
                    />
                    <Button icon={<ReloadOutlined />} onClick={() => window.location.reload()} />
                  </Space>
                </div>
              }
              className="section-card"
            >
              <div className="tab-content">
                <p>ServiceMonitor 信息将显示在这里</p>
              </div>
            </Card>
          </div>
        </div>
      </Content>
    </Layout>
  );
};

export default VersionDetailPage;
